//
//  ScanQRCodeViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/20.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "ScanQRCodeViewController.h"

#import "QRCodeReaderView.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

#import "TakePhotoViewController.h"

@interface ScanQRCodeViewController ()<QRCodeReaderViewDelegate,AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>

//二维码扫描对象
@property (nonatomic, strong) QRCodeReaderView *readview;
//第一次进入该页面
@property (nonatomic, assign) BOOL isFirst;
//跳转到下一级页面
@property (nonatomic, assign) BOOL isPush;

@end

@implementation ScanQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    PPLog(@"eqModel = %@",self.eqType);
    self.navigationItem.title = @"扫描二维码";
    [self setRightNormalImageNamed:@"light_down" selectImageNamed:@"light_up" action:@selector(openBulb)];
    
    _isFirst = YES;
    _isPush = NO;
    [self initScan];
}

#pragma mark - 手电筒开启关闭 -
- (void)openBulb {
    self.rightBtn.selected = !self.rightBtn.selected;
    if (self.rightBtn.selected) {
        [self turnTorchOn:YES];
    } else {
        [self turnTorchOn:NO];
    }
}

- (void)turnTorchOn:(bool)on {
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        if ([device hasTorch] && [device hasFlash]){
            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}


#pragma mark - 初始化扫描 -
- (void)initScan
{
    if (_readview) {
        [_readview removeFromSuperview];
        _readview = nil;
    }
    
    _readview = [[QRCodeReaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _readview.is_AnmotionFinished = YES;
    _readview.backgroundColor = [UIColor clearColor];
    _readview.delegate = self;
    _readview.alpha = 0;
    [self.view addSubview:_readview];
    
    [UIView animateWithDuration:0.5 animations:^{
        _readview.alpha = 1;
    }completion:^(BOOL finished) {
        
    }];
}


#pragma mark - QRCodeReaderViewDelegate -
- (void)readerScanResult:(NSString *)result {
    
    _readview.is_Anmotion = YES;
    [_readview stop];
    
    // 播放扫描二维码的声音
    SystemSoundID soundID;
    NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"noticeMusic" ofType:@"wav"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID);
    AudioServicesPlaySystemSound(soundID);
    
//    static SystemSoundID shake_sound_male_id = 0;
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"noticeMusic" ofType:@"wav"];
//    if (path) {
//        //注册声音到系统
//        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&shake_sound_male_id);
//        AudioServicesPlaySystemSound(shake_sound_male_id);
//    AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
//    }
//    AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
//    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动

    [self accordingQcode:result];
}

#pragma mark - 扫描结果处理 -
- (void)accordingQcode:(NSString *)eqno
{
//    if (eqno.length != 15) {
//        [self showAlert:NSStringFormat(@"%@\n请扫描正确的设备号!",eqno)];
//        return;
//    }
    
    if (!eqno.length) {
        [self showAlert:@"设备号不能为空！"];
        return;
    }
    
    [self.requestTool eqNoLoginByEqno:eqno success:^(EqnoLoginModel *eqnoModel,int status) {
        switch (status) {
            case 0:
            {
                [self.requestTool queryEquipImgByEqId:eqnoModel.eqId show:NO success:^(NSArray *results) {
                    // PPLog(@"Query img array == %ld",results.count);
                    TakePhotoViewController *tp = [[TakePhotoViewController alloc] init];
                    if (!results) {//上传提交
                        tp.uploadType = UploadImgTypeNormal;
                    } else {//补拍提交
                        tp.uploadType = UploadImgTypeSupplement;
                        tp.installInfo = results[0];
                        NSMutableArray *indexImg = [NSMutableArray array];
                        [results[1] enumerateObjectsUsingBlock:^(NSDictionary *result, NSUInteger idx, BOOL * _Nonnull stop) {
                            [indexImg addObject:result[@"type"]];
                        }];
                        if (indexImg.count >= 3) {
                            [self showAlert:@"信息已提交,正在审核!"];
                            return;
                        }
                        tp.indexImg = indexImg;
                    }
                    if ([self.takePhotoType isEqualToString:@"1"]) {//工单进入
                        tp.takePhotoType = @"1";
                        if (![eqnoModel.eqModel isEqualToString:self.eqType])
                        {// 点击的设备型号和实际设备型号不一致
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"该设备型号和实际设备型号不匹配，请重新选择" preferredStyle:UIAlertControllerStyleAlert];
                            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                [self.navigationController popViewControllerAnimated:YES];
                            }]];
                            [self presentViewController:alert animated:YES completion:nil];
                            return;
                        }
                        
                    } else {//普通登录进入
                        tp.takePhotoType = @"0";
                    }
                    tp.eqnoModel = eqnoModel;
                    [self.navigationController pushViewController:tp animated:YES];
                } failure:^(NSError *error) {
                    PPLog(@"error = %@",error);
                }];
            }
                break;
            case 1:
                [self showAlert:@"信息已提交,正在审核!"];
                break;
            case 2:
                [self showAlert:@"该设备号不存在!"];
                break;
            case 3:
            {
                if ([self.takePhotoType isEqualToString:@"1"]){
                    if (![eqnoModel.eqModel isEqualToString:self.eqType])
                    {// 点击的设备型号和实际设备型号不一致
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"该设备型号和实际设备型号不匹配，请重新选择" preferredStyle:UIAlertControllerStyleAlert];
                        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                            [self.navigationController popViewControllerAnimated:YES];
                        }]];
                        [self presentViewController:alert animated:YES completion:nil];
                        return;
                    }
                }
                [self showAlert:@"信息不全,请在平台完善信息!"];
            }
                break;
            default:
                break;
        }
        
    } failure:^(NSError *error) {
        PPLog(@"error = %@",error.description);
    }];
}

- (void)showAlert:(NSString *)message
{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [controller addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reStartScan];// 重新扫码
    }]];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)reStartScan {
    _readview.is_Anmotion = NO;
    
    if (_readview.is_AnmotionFinished) {
        [_readview loopDrawLine];
    }
    
    [_readview start];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.translucent = YES;
    // 导航栏透明
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
//    if (_isFirst || _isPush) {
//        if (_readview) {
//            [self reStartScan];
//        }
//    }
    // 启动扫描
    [self reStartScan];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (_readview) {
        [_readview stop];
        _readview.is_Anmotion = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 导航栏不透明
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (_isFirst) {
        _isFirst = NO;
    }
    if (_isPush) {
        _isPush = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
